package org.budo.xml;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom2.Attribute;
import org.jdom2.Element;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * @author lmw
 */
@Getter
@Setter
@NoArgsConstructor
public class JdomXmlObject extends AbstractXmlObject {
    private Element element;

    public JdomXmlObject(Element element) {
        this.element = element;
    }

    @Override
    public String getNodeName() {
        if (null == this.element) {
            return null;
        }

        return this.element.getName();
    }

    @Override
    public String getTextContent() {
        if (null == this.element) {
            return null;
        }

        return this.element.getText();
    }

    @Override
    public XmlObject[] getChildNodeArray() {
        if (null == this.element) {
            return null;
        }

        List<Element> elements = this.element.getChildren();

        List<XmlObject> xmlObjects = new ArrayList<XmlObject>();
        for (Element element : elements) {
            xmlObjects.add(new JdomXmlObject(element));
        }

        return xmlObjects.toArray(new XmlObject[xmlObjects.size()]);
    }

    @Override
    public Map<String, String> getAttributeMap() {
        if (null == this.element) {
            return null;
        }

        List<Attribute> attributes = this.element.getAttributes();

        Map<String, String> attributeMap = new HashMap<String, String>();
        for (Attribute attribute : attributes) {
            attributeMap.put(attribute.getName(), attribute.getValue());
        }

        return attributeMap;
    }

    @Override
    public XmlObject removeChildNodeByName(String nodeName) {
        if (null == this.element) {
            return null;
        }

        XmlObject[] childNodeArray = this.getChildNodeArrayByName(nodeName);
        for (XmlObject child : childNodeArray) {
            JdomXmlObject _child = (JdomXmlObject) child;
            this.element.removeContent(_child.element);
        }

        return this;
    }
}